import {useState} from 'react';
import SparkMD5 from 'spark-md5';

const useUploadFle = () => {
    // 文件上传
    const [fileList, setFileList] = useState<any>([]);

    // chunkSize 字节大小
    const createChunks = (file: File, chunkSize: number) => {
        const chunks = [];
        for (let i = 0; i < file.size; i += chunkSize) {
            chunks.push(file.slice(i, i + chunkSize));
        }
        return chunks;
    };

    // 文件哈希值计算
    const hash = (chunks: string | any[]) => {
        return new Promise((resolve, reject) => {
            const spark = new SparkMD5();
            const read = (i: number) => {
                if (i >= chunks.length) {
                    resolve(spark.end());
                    return;
                }
                const blob = chunks[i];
                const fileReader = new FileReader();
                fileReader.onload = (e) => {
                    const hash = e?.target?.result;
                    spark.append(hash);
                    read(i + 1);
                };

                fileReader.readAsArrayBuffer(blob);
            };
            read(0);
        });
    };

    return {
        hash,
        fileList,
        createChunks,
        setFileList,
    };
};

export default useUploadFle;
